package project.Servlet;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.json.JSONObject;
import project.Dao.UserDao;
import project.Entity.User;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.text.SimpleDateFormat;
import java.util.*;

import static java.lang.System.out;

public class uploadProfile extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)  {
        System.out.println("执行了doGet");
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response){
        System.out.println("执行了doPost");
    }

    protected void service(HttpServletRequest request, HttpServletResponse response){
        System.out.println("执行了login");
        try {
            process(request, response);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void showDebug(String meg){
        out.println(meg);
    }

    private void deleteProfile(String url){
        String resultMsg="";
        int resultCode=0;

        // 1.获得请求文件名
        String filerelativepath = url;
        int length=filerelativepath.length();
        filerelativepath=filerelativepath.substring(1,length);
        // 去掉绝对路径前的"/",换为"\"
        filerelativepath=filerelativepath.replaceAll("/","\\\\");
        //获取当前文件的绝对路径
        String rootPath = this.getServletContext().getRealPath("/");
        // 3.获取该文件所在路径
        String filePath = rootPath + filerelativepath;
        showDebug("构造的绝对路径是rootPath="+rootPath+" ,文件相对路径是filerelativepath="+filerelativepath+" , 总路径是filepath="+filePath);
        // 4.在指定路径下创建指定名称的文件
        File deleteFile = new File (filePath) ;
        boolean flag = false;
        if (deleteFile.exists()) {
            flag = deleteFile.delete();
            if (flag) {
                resultMsg="ok";
                showDebug("删除成功！");
            } else {
                resultMsg="no";
                showDebug("删除失败！");
            }
        }
        else {
            resultMsg="文件不存在！";
            showDebug("文件不存在！");
        }

    }

    protected void process(HttpServletRequest request, HttpServletResponse response) throws Exception{

        String email = request.getParameter("email");
        String action = request.getParameter("action");
        request.setCharacterEncoding("UTF-8");
        out.println("邮箱:" + email + "\n指令:" + action);
        JSONObject json = new JSONObject();

        switch (action){
            case "upload_profile":
            {
                UserDao userDao = new UserDao();
                List<User> list = userDao.getUserByEmail(email);
                if(list.size()==0){
                    json.put("result", 0);
                    json.put("reason", "获取信息失败！");
                    break;
                }

                ////删除原来的头像
                if(!list.get(0).getUrl().isEmpty())
                    deleteProfile(list.get(0).getUrl());

                String resultMsg="ok";
                int resultCode=0;
                String rootPath = this.getServletContext().getRealPath("/");//获取当前文件的绝对路径
                String savePath = "/";
                String downloadUrl="";                              //传到前端的下载链接
                HashMap<String, String> extMap = new HashMap<String, String>();
                extMap.put("file", "jpg,png,jpeg");//设置上传文件到文件夹file下，文件类型只能...这几类
                long maxSize = 1000000000;//设置上传的文件大小最大为1000000000

                if(ServletFileUpload.isMultipartContent(request)){
                    File uploadDir = new File(rootPath+savePath);//new一个file 路径为rootPath-savePath
                    showDebug("程序自动生成的文件路径是"+rootPath+savePath);
                    // .isDirectory()是检查一个对象是否是文件夹
                    if(!uploadDir.isDirectory()){
                        // mkdirs是新建文件夹，建立文件夹的原则是：如果父文件夹不存在并且最后一级子文件夹不存在，
                        // 它就自动新建所有路经里写的文件夹；如果父文件夹存在，它就直接在已经存在的父文件夹下新建子文件夹。
                        uploadDir.mkdirs();
                    }
                    if(!uploadDir.canWrite()){//上传目录file是否有写入的权限
                        resultMsg = "1";//上传目录没有写权限
                    }else{
                        String dirName = "file";//设置上传目录为file
                        if(!extMap.containsKey(dirName)){//判断上传目录是否正确
                            resultMsg = "2";//目录名不正确
                        }else{
                            savePath += dirName + "/";
                            File saveDirFile = new File(rootPath+savePath);
                            if (!saveDirFile.exists()) {
                                saveDirFile.mkdirs();
                            }
                            File dirFile = new File(rootPath+savePath);
                            if (!dirFile.exists()) {
                                dirFile.mkdirs();
                            }
                            DiskFileItemFactory factory = new DiskFileItemFactory();
                            ServletFileUpload upload = new ServletFileUpload(factory);
                            upload.setHeaderEncoding("UTF-8");
                            List items = null;
                            try {
                                items = upload.parseRequest(request);
                            } catch (FileUploadException e) {
                                e.printStackTrace();
                            }
                            Iterator itr = items.iterator();
                            while (itr.hasNext()) {
                                FileItem item = (FileItem) itr.next();
                                String fileName = item.getName();
                                long fileSize = item.getSize();
                                if (!item.isFormField()) {
                                    //检查文件大小
                                    if(item.getSize() > maxSize){
                                        resultMsg = "3";//上传文件大小超过限制
                                    }else{
                                        showDebug("[file_upload]fileName="+fileName);
                                        String fileExt = fileName.substring(fileName.lastIndexOf(".") + 1).toLowerCase();
                                        if(!Arrays.<String>asList(extMap.get(dirName).split(",")).contains(fileExt)){
                                            resultMsg = "4";//上传文件扩展名是不允许的扩展名
                                        }else{
                                            SimpleDateFormat df = new SimpleDateFormat("yyyyMMddHHmmss");
                                            String newFileName = df.format(new Date()) + "_" + new Random().nextInt(1000) + "." + fileExt;
                                            try{
                                                File uploadedFile = new File(rootPath+savePath, newFileName);
                                                item.write(uploadedFile);
                                                downloadUrl = savePath+newFileName;
                                                resultMsg = "5";//上传文件成功
                                                //写数据库准备
                                            }catch(Exception e){
                                                resultMsg = "6";//上传文件失败
                                            }
                                        }
                                    }
                                }else{
                                    // 这是同步跳转的方式，才会用到这部分；否则用的异步方式，就是上面那部分
                                    //如果是FormField，就是前端的device_id,device_name这些
                                    String fieldName=item.getFieldName();
                                    String fieldValue=item.getString("UTF-8");
                                    showDebug("[upload_file_record][form_field]fieldName="+fieldName+"，fieldValue="+fieldValue);
                                }
                            }
                        }
                    }
                }
                showDebug("[uploadFileRecord]download_url="+downloadUrl+"&result_code="+resultCode+"&resultMsg="+resultMsg);
                //然后返回给前端

                User user = list.get(0);
                user.setProfile_url(downloadUrl);
                if(userDao.updateUser(user)){
                    json.put("result", 1);
                }
                else {
                    json.put("result", 0);
                    json.put("reason", "文件上传出错！");
                }
                break;
            }



        }


        out.println(json);
        //将响应消息返回页面
        response.setContentType("text/html; charset=UTF-8");
        response.getWriter().print(json);
        response.getWriter().flush();
        response.getWriter().close();


    }
}
